package com.dreamchaser.book.filter;

import com.dreamchaser.book.entity.User;
import com.sun.deploy.net.HttpResponse;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Dreamchaser
 */
public class UserFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse= (HttpServletResponse) servletResponse;
        String url=request.getRequestURI();
        if (url.equals("/login")||url.equals("/view/login.html")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        User user= (User) request.getSession().getAttribute("user");
        if (user==null){
            httpResponse.sendRedirect("/view/login.html");
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
